/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.archive.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.dto.EvidenceFile;
import com.icinfo.cloud.provider.common.dto.EvidenceInfo;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.CustomCheckParamUtil;
import com.icinfo.cloud.provider.common.utils.FileUtil;
import com.icinfo.cloud.provider.common.utils.PdfUtil;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.DocumentRelateAttachmentVo;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.ucase.archive.dto.*;
import com.icinfo.cloud.provider.punish.ucase.archive.mapper.CaseElectricArchiveRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.archive.model.CaseElectricArchiveRecord;
import com.icinfo.cloud.provider.punish.ucase.archive.service.ICaseElectricArchiveRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentCatalogChainDetailVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentCatalogChainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentCatalogChainOfflineDetailVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.timevale.tgtext.text.pdf.PdfReader;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 描述:  case_electric_archive_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年12月08日
 */
@Service
public class CaseElectricArchiveRecordServiceImpl extends MyBatisServiceSupport implements ICaseElectricArchiveRecordService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseElectricArchiveRecordServiceImpl.class);
    private static final String DOCUMENT_CATALOG_CODE_DZJZML = "DC2A0223300DZJZML0000000001";
    private static final String DOCUMENT_CATALOG_CODE_DZJZFM = "DC2A0223300DZJZFM0000000001";
    @Resource
    private CaseElectricArchiveRecordMapper caseElectricArchiveRecordMapper;
    @Value("${document.url}")
    private String url;
    @Value("${document.api.uploadBase64File}")
    private String uploadBase64File;

    @Value("${document.api.downloadByUrl}")
    private String downloadByUrl;

    @Resource
    private IStageDocCommonOperateService stageDocCommonOperateService;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;

    @Override
    public List<CaseElectricArchiveRecordDetailVo> getElectricArchiveRecordList(CaseElectricArchivePageQueryDto queryDto) {
        if (queryDto.getLength() > 200) {
            throw new BusinessException("每页条数不能超过200");
        }
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtil.isEmpty(userInfo)) {
            throw new BusinessException("未登录，请先登录");
        }
        checkOrgCode(queryDto);
        queryDto.setUserId(userInfo.getUserId() + "");
        queryDto.setOrgCode(userInfo.getOrgCode());
        PageHelper.startPage(queryDto.getPageNum(), queryDto.getLength());
        List<CaseElectricArchiveRecordDetailVo> list = caseElectricArchiveRecordMapper.selectElectricArchiveRecordList(queryDto);
        //todo 当事人信息处理
//        for (CaseElectricArchiveRecordDetailVo vo:list){
//            List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfo(vo.getCaseId());
//            if (casePartiesRecords.size() > 1) {
//                vo.setPartyName(casePartiesRecords.get(0).getPartyName() + "等" + casePartiesRecords.size() + "个");
//            } else {
//                CasePartiesRecordVo casePartiesRecordVo = casePartiesRecords.get(0);
//                if (PartyTypeEnum.LEGAL.getCode().equals(casePartiesRecordVo.getPartyType())) {
//                    vo.setUniscid(casePartiesRecordVo.getPartyIdentityCode());
//                }
//                vo.setPartyName(casePartiesRecordVo.getPartyName());
//            }
//        }
        return list;
    }

    @Override
    public int saveElectricArchive(CaseElectricArchiveSaveDto saveDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        String caseId = saveDto.getCaseId();
        String archiveId = saveDto.getArchiveId();
        List<CaseElectricArchiveCatalogContent> archiveCatalogContentList = saveDto.getArchiveCatalogContentList();
        // 生成目录
        saveElectricArchiveCatalogDocument(saveDto, archiveCatalogContentList);
        //生成电子卷宗
        String url = this.mergeElectricArchive(saveDto, archiveCatalogContentList);
        CaseElectricArchiveRecord electricArchiveRecord = this.getElectricArchiveRecordByCaseId(caseId);
        if (ObjectUtil.isNotEmpty(electricArchiveRecord)) {
            archiveId = electricArchiveRecord.getId();
        }
        // 处理合并
        LocalDateTime now = LocalDateTime.now();
        CaseElectricArchiveRecord caseElectricArchiveRecord = new CaseElectricArchiveRecord();

        caseElectricArchiveRecord.setArchiveName(saveDto.getArchiveName());
        caseElectricArchiveRecord.setArchiveNumber(saveDto.getArchiveNumber());
        caseElectricArchiveRecord.setUpdateUserId(userInfo.getUserId() + "");
        caseElectricArchiveRecord.setUpdateUserName(userInfo.getRealName());
        caseElectricArchiveRecord.setArchiveUrl(url);
        caseElectricArchiveRecord.setCaseId(caseId);
        JSON json = (JSON) JSONObject.toJSON(archiveCatalogContentList);
        String archiveCatalogContent = json.toJSONString();
        caseElectricArchiveRecord.setArchiveCatalogContent(archiveCatalogContent);
        if (ObjectUtil.isNotEmpty(archiveId)) {
            caseElectricArchiveRecord.setId(archiveId);
            caseElectricArchiveRecord.setUpdateTime(now);
            return caseElectricArchiveRecordMapper.updateByPrimaryKeySelective(caseElectricArchiveRecord);
        } else {
            List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfo(caseId);
            if (casePartiesRecords.size() > 1) {
                caseElectricArchiveRecord.setPartyName(casePartiesRecords.get(0).getPartyName() + "等" + casePartiesRecords.size() + "个");
            } else {
                CasePartiesRecordVo casePartiesRecordVo = casePartiesRecords.get(0);
                caseElectricArchiveRecord.setPartyName(casePartiesRecordVo.getPartyName());
            }
            caseElectricArchiveRecord.setId(BaseUtil.createUid());
            caseElectricArchiveRecord.setCreateUserId(userInfo.getUserId() + "");
            caseElectricArchiveRecord.setCreateUserName(userInfo.getRealName());
            caseElectricArchiveRecord.setUpdateTime(now);
            caseElectricArchiveRecord.setCreateTime(now);
            caseElectricArchiveRecord.setIsDelete(Constant.STRING_0);
            return caseElectricArchiveRecordMapper.insertSelective(caseElectricArchiveRecord);
        }
    }

    @Override
    public List<CaseElectricArchiveCatalogContent> calculateElectricArchivePageNumber(List<CaseElectricArchiveCatalogContent> catalogContentList) {
        int allPage = 0;
        int startPage = 0;
        int sort = 1;
        for (CaseElectricArchiveCatalogContent catalogContent : catalogContentList) {
            try {
                int pages = catalogContent.getDocumentEvidenceUrl().endsWith(".pdf") ? this.getPageNumber(catalogContent.getDocumentEvidenceUrl()) : 1;
                String pageNumber = "";
                startPage = allPage + 1;
                allPage = allPage + pages;
                if (pages <= 1) {
                    pageNumber = startPage + "";
                } else {
                    pageNumber = startPage + "-" + allPage + "";
                }
                catalogContent.setPageNumber(pageNumber);
                catalogContent.setPageCount(pages);
                catalogContent.setSort(sort);
                sort++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return catalogContentList;
    }

    @Override
    public String mergeElectricArchive(CaseElectricArchiveSaveDto saveDto, List<CaseElectricArchiveCatalogContent> catalogContentList) {
        String caseId = saveDto.getCaseId();
        //生成目录
        CaseDocumentRecord ml = caseDocumentRecordService.getCaseDocumentRecord(caseId, DOCUMENT_CATALOG_CODE_DZJZML);
        // 查询封面
        CaseDocumentRecord fm = caseDocumentRecordService.getCaseDocumentRecord(caseId, DOCUMENT_CATALOG_CODE_DZJZFM);

        JSONObject fmJsonObject = JSON.parseObject(fm.getDocumentContent());
        String archiveNumber = fmJsonObject.get("documentNumber").toString();
        saveDto.setArchiveNumber(archiveNumber);

        //合并文件
        List<String> fileUrlList = new ArrayList<>();
        int pageStartNumber = 1;
        if (ObjectUtil.isNotEmpty(fm.getDocumentUrl())) {
            fileUrlList.add(fm.getDocumentUrl());
        }
        if (ObjectUtil.isNotEmpty(ml.getDocumentUrl())) {
            fileUrlList.add(ml.getDocumentUrl());
            pageStartNumber = pageStartNumber + this.getPageNumber(ml.getDocumentUrl());
        }

        for (CaseElectricArchiveCatalogContent catalogContent : catalogContentList) {
            CustomCheckParamUtil.doCheck(catalogContent);
            // 转换文件格式 jpg、png、bmp
            if (!catalogContent.getDocumentEvidenceUrl().endsWith(".pdf")) {
                byte[] pdfByte = PdfUtil.getPdfByte(catalogContent.getDocumentEvidenceUrl());
                String url = uploadToOss(pdfByte);
                if (StringUtils.isNotBlank(url)) {
                    fileUrlList.add(url);
                }
            } else {
                fileUrlList.add(catalogContent.getDocumentEvidenceUrl());
            }
        }
//        byte[] bytes = PdfUtil.mergePdfFilesWithPageNumber(fileUrlList, pageStartNumber);
        byte[] bytes = mergePdfFilesWithPageNumber(fileUrlList, pageStartNumber);
        return uploadToOss(bytes);
    }

    public byte[] mergePdfFilesWithPageNumber(List<String> fileUrlList, int startPage) {
        byte[] desFileBuffer = null;
        FileInputStream fis = null;
        String dir = "pdfFiles";
        String dirFilePath = dir + File.separator + "mergePdf";
        String outputFilePath = dirFilePath + File.separator + BaseUtil.createUid() + ".pdf";
        File fileMkd = new File(dirFilePath);
        File outputFile = new File(outputFilePath);
        try {
            //pdf临时生成目录
            if (!fileMkd.exists()) {
                fileMkd.mkdirs();
            }
            outputFile.createNewFile();
            PDFMergerUtility merger = new PDFMergerUtility();
            for (String e : fileUrlList) {
                byte[] bytes = Base64.decodeBase64(downloadByUrl(e));
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                merger.addSource(byteArrayInputStream);
            }
            merger.setDestinationFileName(outputFilePath);
            // 合并PDF
            merger.mergeDocuments(null);
            fis = new FileInputStream(outputFilePath);
            PdfUtil.addPageNum(fis, outputFilePath, startPage);
            fis = new FileInputStream(outputFilePath);
            desFileBuffer = FileUtil.InputStreamToByte(fis);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputFile.delete();
            fileMkd.delete();
        }
        return desFileBuffer;
    }

    private String uploadToOss(byte[] bytes) {
        //上传签章后的文件到oss
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileBytes", bytes);
        jsonObject.put("fileType", "pdf");
        jsonObject.put("fileName", "");
        JSONObject parseObject = JSON.parseObject(HttpUtil.post(url + uploadBase64File, jsonObject.toString()));
        String cd = "code";
        int th = 200;
        if (parseObject.getInteger(cd) == th) {
            String url = parseObject.getJSONObject("data").getString("ossUrl");
            logger.info("上传文件地址：{}", url);
            return url;
        } else {
            logger.info("上传文件失败,result:{}", parseObject.toString());
            //throw new BusinessException("上传文件失败：" + jsonObject.getString("message"));
            return "";
        }
    }

    /**
     * 下载签章数据
     *
     * @param oosUrl
     * @return
     */
    private String downloadByUrl(String oosUrl) {
        //上传签章后的文件到oss
        HashMap<String, Object> param = new HashMap<>();
        param.put("url", oosUrl);
        JSONObject parseObject = JSON.parseObject(HttpUtil.get(url + downloadByUrl, param));
        String cd = "code";
        int th = 200;
        if (parseObject.getInteger(cd) == th) {
            return parseObject.getString("data");
        }
        logger.info("下载数据的byte失败,result:{}", parseObject.toJSONString());
        throw new BusinessException("下载数据的byte失败：" + parseObject.toJSONString());

    }

    /**
     * 描述保存电子档案目录文档
     *
     * @param saveDto                   保存dto
     * @param archiveCatalogContentList 归档文件目录内容列表
     * @author shishengyao
     * @date 2022/12/13
     */
    private void saveElectricArchiveCatalogDocument(CaseElectricArchiveSaveDto saveDto, List<CaseElectricArchiveCatalogContent> archiveCatalogContentList) {
        String caseId = saveDto.getCaseId();
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        saveDto.setArchiveName(caseMainInfo.getCaseName() + "卷宗");
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
        // todo 电子卷宗文书目录编码写死
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("archiveCatalogContentList", archiveCatalogContentList);
        dataMap.put("orgStandardName", sysDepartParam.getOrgStandardName());
        StageDocCommonOperateSaveDto commonOperateSaveDto = new StageDocCommonOperateSaveDto();
        commonOperateSaveDto.setDataMap(dataMap);
        commonOperateSaveDto.setCaseId(caseId);
        commonOperateSaveDto.setDocumentCatalogCode(DOCUMENT_CATALOG_CODE_DZJZML);
        stageDocCommonOperateService.saveDocInfo(commonOperateSaveDto);
    }

    @Override
    public CaseElectricArchiveRecord getElectricArchiveRecordByCaseId(String caseId) {
        Example example = new Example(CaseElectricArchiveRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        List<CaseElectricArchiveRecord> caseElectricArchiveRecords = caseElectricArchiveRecordMapper.selectByExample(example);
        if (ObjectUtil.isNotEmpty(caseElectricArchiveRecords) && caseElectricArchiveRecords.size() > 0) {
            return caseElectricArchiveRecords.get(0);
        }
        return null;
    }

    @Override
    public List<CaseElectricArchiveCatalogContent> getCaseElectricArchiveDocumentList(CaseElectricArchiveCatalogDocumentQueryDto queryDto) {
        CaseElectricArchiveRecord electricArchiveRecord = this.getElectricArchiveRecordByCaseId(queryDto.getCaseId());
        List<CaseElectricArchiveCatalogContent> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(electricArchiveRecord) && ObjectUtil.isNotEmpty(electricArchiveRecord.getArchiveCatalogContent())) {
            String archiveCatalogContent = electricArchiveRecord.getArchiveCatalogContent();
            if (!ObjectUtils.isEmpty(archiveCatalogContent) && archiveCatalogContent.startsWith(Constant.STRING_LEFT_PARENTHESE)
                    && archiveCatalogContent.endsWith(Constant.STRING_RIGHT_PARENTHESE)) {
                JSONArray jsonArray = JSONArray.parseArray(archiveCatalogContent);
                if (!ObjectUtils.isEmpty(jsonArray) && jsonArray.size() > 0) {
                    //解析
                    for (Object e : jsonArray) {
                        JSONObject jsonoBject = (JSONObject) e;
                        CaseElectricArchiveCatalogContent catalogContent = jsonoBject.toJavaObject(CaseElectricArchiveCatalogContent.class);
                        list.add(catalogContent);
                    }
                }
            }
        } else {
            list = caseElectricArchiveRecordMapper.selectCaseElectricArchiveDocumentList(queryDto);
            //计算页码
            list = calculateElectricArchivePageNumber(list);

        }
        return list;
    }

    @Override
    public List<CaseElectricArchiveRecordDetailVo> getElectricArchiveRecordListToSee(CaseElectricArchivePageQueryDto queryDto) {
        if (queryDto.getLength() > 200) {
            throw new BusinessException("每页条数不能超过200");
        }
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtil.isEmpty(userInfo)) {
            throw new BusinessException("未登录，请先登录");
        }
        createParam(queryDto);
        PageHelper.startPage(queryDto.getPageNum(), queryDto.getLength());
        return caseElectricArchiveRecordMapper.selectElectricArchiveRecordList(queryDto);
    }

    @Override
    public List<ElectricInfoVo> getElectricArchiveList(String caseId) {
        List<CaseDocumentCatalogChainInfoVo> caseDocumentCatalogChainInfoVos = caseMainInfoService.doGetCaseDocumentCatalogChainInfos(caseId);
        ArrayList<ElectricInfoVo> electricInfoVos = new ArrayList<>();
        for (CaseDocumentCatalogChainInfoVo caseDocumentCatalogChainInfoVo : caseDocumentCatalogChainInfoVos) {
            ElectricInfoVo electricInfoVo = new ElectricInfoVo();
            electricInfoVo.setTitle(caseDocumentCatalogChainInfoVo.getStageName());
            List<CaseDocumentCatalogChainDetailVo> caseDocumentCatalogChainDetailVoList = caseDocumentCatalogChainInfoVo.getCaseDocumentCatalogChainDetailVoList();
            ArrayList<ElectricInfoItemVo> electricInfoItemVos = new ArrayList<>();
            for (CaseDocumentCatalogChainDetailVo caseDocumentCatalogChainDetailVo : caseDocumentCatalogChainDetailVoList) {
                if ("电子卷宗".equals(caseDocumentCatalogChainDetailVo.getDocumentKindName())) {
                    continue;
                }
                ElectricInfoItemVo electricInfoItemVo = new ElectricInfoItemVo();
                electricInfoItemVo.setDocumentEvidenceName(caseDocumentCatalogChainDetailVo.getDocumentKindName());
                electricInfoItemVo.setDocumentEvidenceId(caseDocumentCatalogChainDetailVo.getDocumentId());
                electricInfoItemVo.setDocumentEvidenceUrl(caseDocumentCatalogChainDetailVo.getDocumentUrl());
                electricInfoItemVo.setDocumentEvidenceCode(caseDocumentCatalogChainDetailVo.getDocumentCatalogCode());
                electricInfoItemVo.setDocumentNumber(caseDocumentCatalogChainDetailVo.getDocumentNumber());
                electricInfoItemVos.add(electricInfoItemVo);
            }
            // 附件
            for (CaseDocumentCatalogChainDetailVo caseDocumentCatalogChainDetailVo : caseDocumentCatalogChainDetailVoList) {
                List<DocumentRelateAttachmentVo> documentRelateAttachmentList = caseDocumentCatalogChainDetailVo.getDocumentRelateAttachmentList();
                for (DocumentRelateAttachmentVo documentRelateAttachmentVo : documentRelateAttachmentList) {
                    ElectricInfoItemVo electricInfoItemVo = new ElectricInfoItemVo();
                    electricInfoItemVo.setDocumentEvidenceName(documentRelateAttachmentVo.getAttachmentTitle());
                    electricInfoItemVo.setDocumentEvidenceId(documentRelateAttachmentVo.getAttachmentId());
                    electricInfoItemVo.setDocumentEvidenceUrl(documentRelateAttachmentVo.getAttachmentUrl());
                    electricInfoItemVo.setDocumentEvidenceCode("-");
                    electricInfoItemVo.setDocumentNumber(documentRelateAttachmentVo.getAttachmentType());
                    electricInfoItemVos.add(electricInfoItemVo);
                }
            }
            // 线下文书.
            List<CaseDocumentCatalogChainOfflineDetailVo> documentOfflineDetailVoList = caseDocumentCatalogChainInfoVo.getDocumentOfflineDetailVoList();
            for (CaseDocumentCatalogChainOfflineDetailVo caseDocumentCatalogChainOfflineDetailVo : documentOfflineDetailVoList) {
                ElectricInfoItemVo electricInfoItemVo = new ElectricInfoItemVo();
                electricInfoItemVo.setDocumentEvidenceName(caseDocumentCatalogChainOfflineDetailVo.getDocumentTittle());
                electricInfoItemVo.setDocumentEvidenceId(caseDocumentCatalogChainOfflineDetailVo.getCaseStageName());
                electricInfoItemVo.setDocumentEvidenceUrl(caseDocumentCatalogChainOfflineDetailVo.getDocumentUrl());
                electricInfoItemVo.setDocumentEvidenceCode(caseDocumentCatalogChainOfflineDetailVo.getCaseStageCode());
                electricInfoItemVo.setDocumentNumber(caseDocumentCatalogChainOfflineDetailVo.getDocumentCatalogCode());
                electricInfoItemVos.add(electricInfoItemVo);
            }
            electricInfoVo.setItem(electricInfoItemVos);
            electricInfoVos.add(electricInfoVo);
        }
        // 拼接证据
        // todo 测试证据案件号
//        caseId = "02f649acf96d47189002ff62cb31e9ca";
        List<EvidenceInfo> caseEvidenceInfo = evidenceInventoryService.getCaseEvidenceInfo(caseId, true);
        if (CollectionUtils.isNotEmpty(caseEvidenceInfo)) {
            for (EvidenceInfo evidenceInfo : caseEvidenceInfo) {
                ElectricInfoVo electricInfoVo = new ElectricInfoVo();
                electricInfoVo.setTitle(evidenceInfo.getEvidenceTypeName());
                ArrayList<ElectricInfoItemVo> electricInfoItemVos = new ArrayList<>();
                for (EvidenceFile evidenceFile : evidenceInfo.getFileList()) {
                    ElectricInfoItemVo electricInfoItemVo = new ElectricInfoItemVo();
                    electricInfoItemVo.setDocumentEvidenceName(evidenceInfo.getEvidenceName());
                    electricInfoItemVo.setDocumentNumber(evidenceFile.getFileName());
                    electricInfoItemVo.setDocumentEvidenceUrl(evidenceFile.getFileUrl());
                    electricInfoItemVo.setDocumentEvidenceId(evidenceInfo.getEvidenceUid());
                    electricInfoItemVo.setDocumentEvidenceCode(evidenceInfo.getEvidenceUid());
                    electricInfoItemVos.add(electricInfoItemVo);
                }
                electricInfoVo.setItem(electricInfoItemVos);
                electricInfoVos.add(electricInfoVo);
            }
        }
        return electricInfoVos;
    }


    /**
     * orgCode处理
     *
     * @param queryDto 查询dto
     * @author shishengyao
     * @date 2022/12/08
     */
    private void checkOrgCode(CaseElectricArchivePageQueryDto queryDto) {
        queryDto.setOrg(0);
        if (StringUtils.isEmpty(queryDto.getOrgCode())) {
            return;
        }
        setParam(queryDto);
    }

    /**
     * 查询的数据
     *
     * @param queryDto
     */
    private void createParam(CaseElectricArchivePageQueryDto queryDto) {
        if (StringUtils.isEmpty(queryDto.getOrgCode())) {
            queryDto.setOrgCode(UserUtil.getUserInfo().getOrgCode());
        }
        setParam(queryDto);
    }

    private void setParam(CaseElectricArchivePageQueryDto queryDto) {
        List<String> orgCodeList = new ArrayList<>();
        List<String> deptCodeList = new ArrayList<>();
        String[] str = queryDto.getOrgCode().split(",");

        for (String s : str) {
            if (s.indexOf("_") > 0) {
                orgCodeList.add(s);
            } else {
                deptCodeList.add(s);
            }
        }
        if (orgCodeList.size() > 0 && deptCodeList.size() > 0) {
            queryDto.setOrg(1);
        } else if (orgCodeList.size() > 0) {
            queryDto.setOrg(2);
        } else if (deptCodeList.size() > 0) {
            queryDto.setOrg(3);
        }
        queryDto.setOrgCodeList(orgCodeList);
        queryDto.setDeptCodeList(deptCodeList);
    }


    public int getPageNumber(String pdfUrl) {
        int pages = 0;
        PdfReader pdfReader = null;
        try {
            pdfReader = new PdfReader(Base64.decodeBase64(downloadByUrl(pdfUrl)));
            pages = pdfReader.getNumberOfPages();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pdfReader != null) {
                pdfReader.close();
            }
        }
        return pages;
    }
}
